package CyclicBarrier_6;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class 多阶段任务_游戏玩家准备 {
    public static void main(String[] args) {
        final int PLAYER_COUNT = 4;
        final int PHASE_COUNT = 3;
        final CyclicBarrier barrier = new CyclicBarrier(PLAYER_COUNT, new Runnable() {
            private int phase = 1;
            public void run() {
                System.out.println("所有玩家完成阶段 " + phase + "，进入下一阶段");
                phase++;
            }
        });

        for (int i = 0; i < PLAYER_COUNT; i++) {
            final int playerId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        for (int phase = 1; phase <= PHASE_COUNT; phase++) {
                            System.out.println("玩家-" + playerId + " 开始阶段 " + phase + " 准备");
                            Thread.sleep((long)(Math.random() * 1000 + 500));
                            System.out.println("玩家-" + playerId + " 完成阶段 " + phase + " 准备");
                            barrier.await();
                        }
                        System.out.println("玩家-" + playerId + " 全部准备完成");
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}